package com.company.project.search.service.Impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.project.search.engine.Param;
import com.company.project.search.entity.Search;
import com.company.project.search.mapper.SearchMapper;
import com.company.project.search.service.SearchEsService;
import com.company.project.search.service.SearchService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SearchServiceImpl extends ServiceImpl<SearchMapper, Search> implements SearchService {

    @Resource
    private SearchEsService searchEsService;


    @Override
    public void saveOrUpdate(List<Search> list) {

        this.saveOrUpdateBatch(list);

    }

    @Override
    public List<Search> esQuery(Param p) {
        // 构建查询条件
        // 第一个参数是页数page，第二个参数是每页数据数量pageSize 从0开始
        Pageable pageable = PageRequest.of(p.curPage-1, 1);
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        // 添加基本分词查询
        queryBuilder.withQuery(QueryBuilders.matchQuery("name", "*"+p.keyword+"*"));
        queryBuilder.withPageable(pageable);
        //QueryBuilders.fuzzyQuery("content", "web")
        // 搜索，获取结果
        Page<Search> items = this.searchEsService.search(queryBuilder.build());
        // 总条数
        long total = items.getTotalElements();
        System.out.println("total = " + total);
        for (Search item : items) {
            System.out.println(item);
        };
        List<Search> list = items.getContent();
        return list;
    }
}
